package com.sany.taskmanager.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sany.taskmanager.bean.FactoryBean;
import com.sany.taskmanager.databinding.ItemFactoryBinding;

import java.util.List;

public class FactoryAdapter extends RecyclerView.Adapter<FactoryAdapter.VH> {

    private final Context mContext;
    private List<FactoryBean> mFactoryList;

    private int selectedIndex;

    public FactoryAdapter(Context context) {
        mContext = context;
    }

    public void setList(List<FactoryBean> factoryList, int selectedIndex) {
        this.mFactoryList = factoryList;
        this.selectedIndex = selectedIndex;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemFactoryBinding itemFactoryBinding = ItemFactoryBinding.inflate(LayoutInflater.from(mContext), parent, false);
        return new VH(itemFactoryBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        FactoryBean item = mFactoryList.get(position);
        holder.tvFactory.setText(item.getFactoryName());
        if (selectedIndex == position) {
            holder.tvFactory.setSelected(true);
        } else {
            holder.tvFactory.setSelected(false);
        }
        holder.itemView.setOnClickListener(v -> {
            selectedIndex = holder.getAdapterPosition();
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return mFactoryList == null ? 0 : mFactoryList.size();
    }

    public int getSelectedIndex() {
        return selectedIndex;
    }

    static class VH extends RecyclerView.ViewHolder {
        public TextView tvFactory;

        public VH(@NonNull ItemFactoryBinding itemFactoryBinding) {
            super(itemFactoryBinding.getRoot());
            tvFactory = itemFactoryBinding.tvFactory;
        }
    }
}
